package com.ruoyi.web.controller.system;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.net.URL;
import java.util.*;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.ruoyi.common.utils.JAESUtil;
import com.ruoyi.common.utils.QywxUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.MatrixToImageWriter;
import com.ruoyi.common.utils.sign.AESUtils;
import com.ruoyi.common.utils.vo.DeptUserVO;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysMenu;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginBody;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysMenuService;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录验证
 * 
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 登录方法
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }


    @PostMapping("/qyLogin")
    public AjaxResult qyLogin(@RequestParam("code")String code){
        AjaxResult ajax = AjaxResult.success();
        Map<String,String> map = QywxUtil.getUserId(QywxUtil.getToken(), code);
        String userId = map.get("userId");
        String userTicket =  map.get("userTicket");
        if (userId == null){
            return AjaxResult.error();
        }
        SysUser user = sysUserService.selectUserByCode(userId);
        if (user != null){
            DeptUserVO authUserInfo = QywxUtil.getAuthUserInfo(QywxUtil.getToken(), userTicket);
            if (authUserInfo != null && StringUtils.isNotEmpty(authUserInfo.getUserId())){
                user.setAvatar(authUserInfo.getAvatar());
                user.setPhonenumber(authUserInfo.getMobile());
                user.setSex(authUserInfo.getGender()== "1" ? "0" : (authUserInfo.getGender() == "2" ? "1" : "2" ));
                sysUserService.update(user);
            }

        }
        String token = loginService.codeLogin(userId);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        SysUser sysUser = sysUserService.selectUserById(user.getUserId());
        user.setAvatar(sysUser.getAvatar());
        user.setPhonenumber(sysUser.getPhonenumber());
        user.setDuties(sysUser.getDuties());
        user.setPlate(sysUser.getPlate());
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    @GetMapping("/getJSAPI")
    public AjaxResult getJSAPI(@RequestParam("url")String url){
        String ticket = QywxUtil.getTicket(QywxUtil.getToken());
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        String nonceStr = UUID.randomUUID().toString();
        String signature = QywxUtil.getSignature(timestamp, ticket, nonceStr, url);

        Map<String, String> map = new HashMap<>();
        map.put("timestamp", timestamp);
        map.put("nonceStr", nonceStr);
        map.put("signature", signature);
//        System.out.println(JSONObject.toJSONString(map));
        return AjaxResult.success(map);
    }
}
